package com.example.restatr.Adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.example.restatr.Atcivity.GarbageClassification.GarbageClassificationAt;
import com.example.restatr.Bean.NewsBean;
import com.example.restatr.Atcivity.ContentAt;
import com.example.restatr.Atcivity.Main.LoginAt;
import com.example.restatr.Atcivity.Main.MainActivity;
import com.example.restatr.R;
import com.example.restatr.Tools;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class NewsListAdapter extends RecyclerView.Adapter<NewsListAdapter.XwViewHolder> {
    private Context context;
    private ArrayList<NewsBean.RowsBean> objects;
    private NewsListAdapter xwListAdapter;
    private String likeLink;

    public NewsListAdapter(Context context, ArrayList<NewsBean.RowsBean> objects, String likeLink) {
        this.context = context;
        this.objects = objects;
        this.likeLink = likeLink;
    }

    public void setXwListAdapter(NewsListAdapter xwListAdapter) {
        this.xwListAdapter = xwListAdapter;
    }

    @NonNull
    @Override
    public NewsListAdapter.XwViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View inflate = LayoutInflater.from(context).inflate(R.layout.xw_card_item, parent, false);
        NewsListAdapter.XwViewHolder xwViewHolder = new NewsListAdapter.XwViewHolder(inflate);
        return xwViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull final NewsListAdapter.XwViewHolder holder, final int position) {

        if (objects.size() != 0) {
            if (objects.get(position).getCover() != null) {
                Glide.with(context)
                        .load(Tools.ip + objects.get(position).getCover())
                        .transform(new RoundedCorners(15))
                        .placeholder(R.drawable.bj)
                        .error(R.drawable.bj)
                        .into(holder.tp);
            } else {
                Glide.with(context)
                        .load(Tools.ip + objects.get(position).getImgUrl())
                        .transform(new RoundedCorners(15))
                        .placeholder(R.drawable.bj)
                        .error(R.drawable.bj)
                        .into(holder.tp);
                holder.bottomLl.setVisibility(View.GONE);
            }

            holder.title.setText(objects.get(position).getTitle());
            holder.likeNum.setText(String.valueOf(objects.get(position).getLikeNum()));
            holder.ReadNum.setText(objects.get(position).getReadNum());
            if (objects.get(position).getCommentNum() != null) {
                holder.commentNum.setText(objects.get(position).getCommentNum());
            } else {
                holder.commentNum.setText("0");
            }

            holder.date.setText(objects.get(position).getPublishDate());
        }

        final boolean[] isLike = {false};
        if (MainActivity.info!=null&&MainActivity.info.equals("lj")) {
            holder.Rl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    GetContent(objects.get(position).getId(),position, context);
                }
            });
        } else {
            //新闻详情
            holder.Rl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, ContentAt.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra("title", objects.get(position).getTitle());
                    intent.putExtra("content", String.valueOf(objects.get(position).getContent()));
                    intent.putExtra("date", objects.get(position).getPublishDate());
                    intent.putExtra("likeNum", objects.get(position).getLikeNum());
                    intent.putExtra("ReadNum", Integer.parseInt(objects.get(position).getReadNum()));
                    intent.putExtra("commentNum", String.valueOf(objects.get(position).getCommentNum()));
                    intent.putExtra("id", objects.get(position).getId());
                    intent.putExtra("isLike", isLike[0]);
                    intent.putExtra("type", "default");
                    context.startActivity(intent);
                }
            });
        }

        //新闻点赞
        holder.dianz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            int LoginCode = MainActivity.sp.getInt("code", 0);
                            if (LoginCode == 200 & !isLike[0]) {
                                final String put = Tools.Put(likeLink + objects.get(position).getId(), MainActivity.sp.getString("token", null), "");
                                JSONObject jx = new JSONObject(put);
                                final int code = jx.getInt("code");
                                final String msg = jx.getString("msg");
                                ((Activity) context).runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                                        if (code == 200) {
                                            objects.get(position).setLikeNum(objects.get(position).getLikeNum() + 1);
                                            holder.likeNum.setText(String.valueOf(objects.get(position).getLikeNum()));
                                            holder.likeImage.setImageResource(R.drawable.ic_baseline_favorite_24);
                                            isLike[0] = true;
                                        }
                                    }
                                });
                            } else if (LoginCode != 200) {
                                Toast.makeText(context, "您还未登入！", Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(context, LoginAt.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                context.startActivity(intent);
                            } else {
                                ((Activity) context).runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        objects.get(position).setLikeNum(objects.get(position).getLikeNum() - 1);
                                        holder.likeNum.setText(String.valueOf(objects.get(position).getLikeNum()));
                                        holder.likeImage.setImageResource(R.drawable.ic_baseline_favorite_border_24);
                                        isLike[0] = false;
                                    }
                                });
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

            }
        });
    }

    private void GetContent(int id,int pos, Context context) {
        new Thread(() -> {
            try {
                String token = Tools.Get("/prod-api/api/garbage-classification/news/" + id, MainActivity.sp.getString("token", ""));
                JSONObject jsonObject = new JSONObject(token);
                String string = jsonObject.getJSONObject("data").getString("content");
                objects.get(pos).setContent(new StringBuilder(string));
                ((Activity) context).runOnUiThread(() -> {
                    Intent intent = new Intent(context, ContentAt.class);
                    intent.putExtra("title", objects.get(pos).getTitle());
                    intent.putExtra("content", String.valueOf(objects.get(pos).getContent()));
                    intent.putExtra("id", id);
                    intent.putExtra("type", "lj");
                    context.startActivity(intent);
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }).start();
    }

    @Override
    public int getItemCount() {
        return objects.size();
    }

    class XwViewHolder extends RecyclerView.ViewHolder {
        ImageView tp;
        TextView title;
        TextView likeNum;
        TextView ReadNum;
        TextView commentNum;
        TextView date;
        CardView Rl;
        LinearLayout dianz;
        ImageView likeImage;
        LinearLayout bottomLl;

        public XwViewHolder(@NonNull View itemView) {
            super(itemView);
            tp = itemView.findViewById(R.id.tp);
            title = itemView.findViewById(R.id.title);
            likeNum = itemView.findViewById(R.id.likeNum);
            ReadNum = itemView.findViewById(R.id.ReadNum);
            commentNum = itemView.findViewById(R.id.commentNum);
            date = itemView.findViewById(R.id.date);
            Rl = itemView.findViewById(R.id.Rl);
            dianz = itemView.findViewById(R.id.dianz);
            likeImage = itemView.findViewById(R.id.likeImage);
            bottomLl = itemView.findViewById(R.id.bottom_ll);
        }
    }
}
